package com.cl.blog.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Author 付
 * @Date 2024-03-14 17:41
 * @Version 1.0
 * @description
 * @since 1.0
 */
@Slf4j
@Data
@Component
@ConfigurationProperties("jwt")
public class JwtUtil {
	private String secret;
	private long expire;

	/**
	 * 生成token
	 */
	public  String generateToken(long userId,String issuer){
		Date date = new Date();
		// 过期时间
		Date expireDate = new Date(date.getTime() + expire * 1000);
		return Jwts.builder()
				.setHeaderParam("typ","JWT")
				.setSubject(userId + "")
				.setIssuedAt(date)
				.setIssuer(issuer)
				.setExpiration(expireDate)
				.signWith(SignatureAlgorithm.HS512,secret)
				.compact();
	}

	/**
	 * 解析token
	 * @param token
	 * @return
	 */
	public Claims getClaimByToken(String token,String issuer){
		try {
			Claims claims = Jwts.parser()
					.setSigningKey(secret)
					.parseClaimsJws(token)
					.getBody();
			if (!issuer.equals(claims.getIssuer())|| issuer==null) {
				return null;
			}
			return claims;
		}catch (Exception e){
			log.debug("validDate is token error------>" + e);
			return  null;
		}
	}

	/**
	 * 判断token是否过期
	 * @param expiration
	 * @return true 过期
	 */
	public boolean isTokenExpired(Date expiration){
		return expiration.before(new Date());
	}
}
